<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import') ">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width: 100%;">
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              {{ EmployeesEnumFFormat( row.formOfEmployment ) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column sortable prop="timeOfEntry" label="入职时间" />
          <!-- <el-table-column prop="username" label="账户状态" /> -->
          <el-table-column prop="username" label="操作" width="280">
            <template #default="{row}">
              <!-- 查询参数方式 -->
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> -->
              <!-- 路径传参方式 -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="roleShowDialog=true">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page.sync="page"
            :page-size="size"
            layout="total, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hResetForm">
        <addEmployees ref="addEmployees" @colse="showDialog=false" @success="hDoAdd" />
      </el-dialog>

      <el-dialog title="分配角色" :visible.sync="roleShowDialog">
        <AssignRole @close="roleShowDialog = false" />
      </el-dialog>

    </div>
  </div>
</template>
<script>
// 取出枚举的数据
import EmployeesEnum from '@/constant/employees'
import { getEmployees, delEmployee } from '@/api/employees'
import addEmployees from './empDialog.vue'
import AssignRole from './assignRole.vue'
// 声明一个空对象，保存遍历出来的
const hireType = {}
EmployeesEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
console.log(hireType) // {1: '正式', 2: '非正式'}

export default {
  name: 'Employees',
  components: { addEmployees, AssignRole },
  data() {
    return {
      page: 1, // 默认第一页
      size: 5, // 一页几条数据
      list: [],
      total: 0,
      showDialog: false, // 控制弹层开关
      roleShowDialog: false // 控制分配角色弹层显示隐藏
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // excel导出***************************************************************
    handleDownload() {
      //  import('@/vendor/Export2Excel')  懒加载的方式导入一个模块（文件）返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel 指的是模块对象，可以使用excel调用 Export2Excel文件中的函数或者使用Export2Excel文件中的变量

        excel.export_json_to_excel({
          header: ['姓名', '年龄'],
          data:
                [
                  ['曹操', 30],
                  ['孙权', 35]
                ],
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    // 删除角色
    hDel(id) {
      this.$confirm('确认删除吗？').then(async() => {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重发请求
        this.loadEmployees()
      }).catch((error) => {
        console.log(error)
      })
    },
    // 重置表单
    hResetForm() {
      this.$refs.addEmployees.resetForm()
    },
    // 子传父，关闭弹框
    hDoAdd() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees() // 重新渲染
      this.showDialog = false // 关闭弹框
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 格式化聘用形式的函数
    EmployeesEnumFFormat(data) {
      // 将传入的 1 || 2 转化为 正式 || 非正式
      // return EmployeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 获取员工信息
    async loadEmployees() {
      try {
        const { data: res } = await getEmployees(this.page, this.size)
        console.log(res)
        this.list = res.rows
        this.total = res.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
<style>
.employees{
  margin-top: 28px;
}
</style>

